// AUTHORS: Yiwei (Alan) Han, Kevin Lam

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("IE5/6 not supported");
	}
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}


var amazon_req = getXmlHttpRequestObject();

function getAmazonContent(isbn) {
	if (amazon_req.readyState == 4 || amazon_req.readyState == 0) {
		document.getElementById('book-progress').className = "loading";
		amazon_req.open("GET", 'ajax/amazon?isbn=' + isbn, true);
		amazon_req.onreadystatechange = handleAmazonContent;
		amazon_req.send(null);
	}
	else {
		setTimeout("getAmazonContent('"+isbn+"')",100);
	}

}

function handleAmazonContent() {
	if (amazon_req.readyState == 4) {
		var xmlDoc = amazon_req.responseXML;
		var content = document.getElementById('book');
		if (xmlDoc.getElementsByTagName("detail").length > 0) {
		var title = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
		var imageurl = xmlDoc.getElementsByTagName("image")[0].childNodes[0].nodeValue;
		var detailurl = xmlDoc.getElementsByTagName("detail")[0].childNodes[0].nodeValue;
		var newPrice = xmlDoc.getElementsByTagName("newPrice")[0].childNodes[0].nodeValue;
		var usedPrice = xmlDoc.getElementsByTagName("usedPrice")[0].childNodes[0].nodeValue;
		var html = '<div class="info-element" onclick="window.location = \''+unescape(detailurl)+'\';">';
		html +='<div style="float:left; padding-right: 30px;"><img src="'+imageurl+'"/></div><div>';
		html += title;
		html +='&nbsp;Amazon.ca - Lowest prices: New from '+newPrice+', Used from '+usedPrice;
		html +='</div><br style="clear:both;"></div>';
		content.innerHTML += html;
		}
		document.getElementById('book-progress').className = "completed";
	}
}

var sbk_req = getXmlHttpRequestObject();

function getSBKContent(title,author,isbn) {
	if (sbk_req.readyState == 4 ||sbk_req.readyState == 0) {
		document.getElementById('book-progress').className = "loading";
		sbk_req.open("GET", 'ajax/saveonbook?title='+title+'&author='+author+'&isbn=' + isbn, true);
		sbk_req.onreadystatechange = handleSBKContent;
		sbk_req.send(null);
	}
	else {
		setTimeout("getSBKContent('"+title+"','"+author+"','"+isbn+"')",100);
	}

}

function handleSBKContent() {
	
	if (sbk_req.readyState == 4) {
		var xmlDoc = sbk_req.responseXML;
		var content = document.getElementById('book');
		if(xmlDoc.getElementsByTagName("title").length > 0) {
		var title = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
		var detailurl = xmlDoc.getElementsByTagName("detail")[0].childNodes[0].nodeValue;
		var lowestPrice = xmlDoc.getElementsByTagName("lowestPrice")[0].childNodes[0].nodeValue;
		var highestPrice = xmlDoc.getElementsByTagName("highestPrice")[0].childNodes[0].nodeValue;
		var html = '<div class="info-element" onclick="window.location = \''+unescape(detailurl)+'\';">';
		html += title;
		html += '&nbsp;SaveonBook - Price Range: '+lowestPrice+' - '+highestPrice;
		html += '</div>';
		content.innerHTML += html;
		}
		document.getElementById('book-progress').className = "completed";
	}
}

var seat_req = getXmlHttpRequestObject();

function getSeatContent(dept,course,section) {
	if (seat_req.readyState == 4 ||seat_req.readyState == 0) {
		seat_req.open("GET", 'ajax/seats?dept='+dept+'&course='+course+'&section=' + section, true);
		seat_req.onreadystatechange = handleSeatContent;
		seat_req.send(null);
	}
}

function handleSeatContent() {
	if (seat_req.readyState == 4) {
		var xmlDoc = seat_req.responseXML;
		var content = document.getElementById('seat');
		if(xmlDoc.getElementsByTagName("error").length > 0) {
			var error = xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
			content.innerHTML += '<div class="seat-element">'+error+'</div>';
		}
		else {
		var total = xmlDoc.getElementsByTagName("total")[0].childNodes[0].nodeValue;
		var generalRemain = xmlDoc.getElementsByTagName("generalRemain")[0].childNodes[0].nodeValue;
		var restrictedRemain = xmlDoc.getElementsByTagName("restrictedRemain")[0].childNodes[0].nodeValue;
		var registered = xmlDoc.getElementsByTagName("registered")[0].childNodes[0].nodeValue;
		content.innerHTML += '<div class="seat-element">Registered: '+registered+'</div>';
		content.innerHTML += '<div class="seat-element">Total Seats Remaining: '+total+'</div>';
		content.innerHTML += '<div class="seat-element">General Seats Remaining: '+generalRemain+'</div>';
		content.innerHTML += '<div class="seat-element">Restricted Seats Remaining: '+restrictedRemain+'</div>';
		if(total == 0)
			if(getCookie('user') != null)
				content.innerHTML += '<div class="notify-button" onclick="showNotificationRequestDialog();">Request notification</div>';
			else
				content.innerHTML += '<div class="notify-button-nologin">Login to request a notification</div>';
		}
		document.getElementById('seat-progress').className = "completed";
	}
}

function appendWorklistButton(dept,course,section) {
	if (getCookie('user') != null) {
		var content = document.getElementById('title');
		content.innerHTML += '<div class="addToWorklistButton" onclick="addWorklistItem(\''+dept+'\',\''+course+'\',\''+section+'\');">Add to your worklist</div>';
	}
}


var rmp_req = getXmlHttpRequestObject();

function getRMPContent(instructors) {
	if (rmp_req.readyState == 4 ||rmp_req.readyState == 0) {
		rmp_req.open("GET", 'ajax/rmp?instructors='+instructors, true);
		rmp_req.onreadystatechange = handleRMPContent;
		rmp_req.send(null);
	}
}

function handleRMPContent() {
	if (rmp_req.readyState == 4) {
		var xmlDoc = rmp_req.responseXML.documentElement;
		var content = document.getElementById('instructor');
		var xs = xmlDoc.getElementsByTagName("instructor");
		for (i = 0; i < xs.length; i++) {
			var name = xs[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
			var rating = xs[i].getElementsByTagName("rating")[0].childNodes[0].nodeValue;
			var url = xs[i].getElementsByTagName("url")[0].childNodes[0].nodeValue;
			var html = '';
			if(url == 'not found')
				html += '<div class="info-element-no-hover">';
			else
				html +='<div class="info-element" onclick=\'window.location="'+url+'"\'>';
			html += '<p1 class="instructor-info">'+name+'</p1>';
			if(rating != 'not found') {
				html += '<p2 class="instructor-info"><p3 class="header">Rating:&nbsp;&nbsp;</p3>'+rating+'</p2>';
				html += '<p4 class="instructor-source">(Source: RateMyProfessor.com)</p4></div>';
			}
			content.innerHTML += html;
		}
		document.getElementById('instructor-progress').className = "completed";
	}
}

var book_req = getXmlHttpRequestObject();

function getBookContent(dept,course,section) {
	if (book_req.readyState == 4 ||book_req.readyState == 0) {
		book_req.open("GET", 'ajax/book?dept='+dept+'&course='+course+'&section='+section, true);
		book_req.onreadystatechange = handleBookContent;
		book_req.send(null);
	}
}

function handleBookContent() {
	if (book_req.readyState == 4) {
		var xmlDoc = book_req.responseXML;
		var content = document.getElementById('book');
		var error = xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
		if(error == 'none') {
			var xs = xmlDoc.documentElement.getElementsByTagName("book");
		for (i = 0; i < xs.length; i++) {
				var title = xs[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
				var required = xs[i].getElementsByTagName("required")[0].childNodes[0].nodeValue;
				var author = xs[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
				var isbn = xs[i].getElementsByTagName("isbn")[0].childNodes[0].nodeValue;
				var html = '<div class="info-element-no-hover"><p>'+title+'&nbsp;['+required+'] - '+author+'</p>';
				html += '<p style=\'font: 8px "Trebuchet MS";\'>ISBN: '+isbn+ '</p>';
				html += '</div>'
				content.innerHTML += html;
				getAmazonContent(isbn);
				getSBKContent(title,author,isbn);
			}
		}
		document.getElementById('book-progress').className = "completed";
	}
}

function initMap(lat,long) {
	if(lat != '' && long != '') {
	var latlng = new google.maps.LatLng(lat, long);
	var myOptions = {
		zoom : 18,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.HYBRID
	};
	var map = new google.maps.Map(document
			.getElementById("map"), myOptions);
	var marker = new google.maps.Marker({position: latlng});
	marker.setMap(map);
	}
	else {
		document.ElementById("map").innerHTML = "<p class='header'>No building information</p>"
	}
}

function mouseoverelement(div_value){
	div_value.className = "info-element-mouseover";
}

function mouseoutelement(div_value){
	div_value.className = "info-element";
}

function initcontent(){
//	$('#content').animate({ opacity: 0.6, height: 'show' }, 1000);
}

function showNotificationRequestDialog(){
	$('#notification-dialog-container').fadeIn();
	$('#dimmer').fadeIn();
}

function closeNotificationRequestDialog(){
	$('#notification-dialog-container').fadeOut();
	$('#dimmer').fadeOut();
}

var notification_req = getXmlHttpRequestObject();

function sendNotificationRequest(dept,course,section){
	var user = getCookie('user');
	if(user != null) {
		if (notification_req.readyState == 4 ||notification_req.readyState == 0) {
			var seatcfg = 2;
			if(document.getElementById("seatgen").checked)
					seatcfg = 1;
			notification_req.open("GET", 'auth/ajax/notify?dept='+dept+'&course='+course+'&section='+section+'&seatcfg='+seatcfg, true);
			notification_req.onreadystatechange = handleNotificationRequest;
			notification_req.send(null);
		}
	}
}

function handleNotificationRequest(){
	if (notification_req.readyState == 4) {
		var xmlDoc = notification_req.responseXML;
		var content = document.getElementById('notification-error');
		var msg = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
		content.innerHTML = "<p class='notification-error-text'>"+msg+"</p>";
		$('#notification-error').fadeIn(500).delay(3000).fadeOut(500);
		$('#notification-dialog-container').fadeOut();
		$('#dimmer').fadeOut();
	}
}

var add_wlitem_req = getXmlHttpRequestObject();

function addWorklistItem(dept,course,section){
	var user = getCookie('user'); 
	if (user != null ){
		if (add_wlitem_req.readyState == 4 || add_wlitem_req.readyState == 0) {
			add_wlitem_req.open("GET", 'auth/ajax/worklist?action=add&dept='+dept+'&course='+course+'&section='+section, true);
			add_wlitem_req.onreadystatechange = handleAddWorklistItem;
			add_wlitem_req.send(null);
		}
	}
}

function handleAddWorklistItem(){
	if (add_wlitem_req.readyState == 4) {
		var xmlDoc = add_wlitem_req.responseXML;
		var content = document.getElementById('worklist-error');
		var msg = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
		content.innerHTML = "<p class='notification-error-text'>"+msg+"</p>";
		$('#worklist-error').fadeIn(500).delay(3000).fadeOut(500);
	}
}